package com.ququ.syb.mqhandler.service;

import com.ququ.common.result.ResultJson;
import com.ququ.syb.common.constant.ResultStatusConstant;
import com.ququ.syb.common.constant.WithdrawStatusConstant;
import com.ququ.syb.common.pojo.PayChannel;
import com.ququ.syb.common.pojo.WithdrawOrder;
import com.ququ.syb.mqhandler.fegin.ChannelsRouterFegin;
import com.ququ.syb.mqhandler.fegin.PayChannelFegin;
import com.ququ.syb.mqhandler.fegin.WithdrawBusinessFegin;
import com.ququ.syb.mqhandler.fegin.WithdrawOrderFegin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WithdrawYeepaySkbService {

    private Logger logger = LoggerFactory.getLogger(WithdrawYeepaySkbService.class);
    @Autowired
    private ChannelsRouterFegin channelsRouterFegin;
    @Autowired
    private WithdrawOrderFegin withdrawOrderFegin;
    @Autowired
    private WithdrawBusinessFegin withdrawBusinessFegin;
    @Autowired
    private PayChannelFegin payChannelFegin;

    public void doWithdraw(String tradenum){
        WithdrawOrder withdrawOrder = withdrawOrderFegin.queryWithdrawOrder(tradenum).getData();
        if (withdrawOrder == null){
            logger.error("{}提现订单不存在",tradenum);
            return;
        }
        if (withdrawOrder.getStatus() != WithdrawStatusConstant.AUDIT_SUCCESS){
            logger.error("{}提现订单不是审核完成状态，无法重复调用通道提现接口",tradenum);
            return;
        }
        PayChannel payChannel = payChannelFegin.getPayChannel(withdrawOrder.getPaychannelid()).getData();
        if (payChannel.getAllowwithdraw() != null && payChannel.getAllowwithdraw() == 0){
            logger.error("{}通道不允许提现操作，暂不处理",withdrawOrder.getPaychannelid());
            return;
        }
        ResultJson withdrawResult = channelsRouterFegin.withdraw(withdrawOrder.getAccountid(),
                withdrawOrder.getPaychannelid(),
                withdrawOrder.getTradenum(),
                withdrawOrder.getAmount(),
                null,null,null,null,null,null,null,null,null,null,null,null);
        if (withdrawResult.getStatus() == ResultStatusConstant.SUCCESS){
            //提现操作成功，等待回调
            withdrawOrder.setExcutetime(new Date());
            withdrawOrder.setStatus(WithdrawStatusConstant.ACCEPTING);
            withdrawOrderFegin.updateWithdrawOrder(withdrawOrder);
        }else {
            //提现操作失败
            withdrawBusinessFegin.withdrawCallback(tradenum,0,withdrawResult.getMsg());
        }
    }
}
